package com.xyazm.order.statemachine.action.order.create.node;

import com.xyazm.inventory.domain.param.DeductProductParam;
import com.xyazm.inventory.domain.param.ReleaseProductStockParam;
import com.xyazm.order.domain.param.CreateOrderParam;
import com.xyazm.order.mapstruct.OrderApiMapstruct;
import com.xyazm.order.remote.InventoryRemote;
import com.xyazm.process.engine.process.ProcessContext;
import com.xyazm.process.engine.process.RollbackProcessor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * 锁定库存节点，异常可回滚
 * @author xuyou
 * @date 2023年02月02日 21:22
 */
@Component
public class CreateOrderDeductStockNode extends RollbackProcessor {

    @Autowired
    private InventoryRemote inventoryRemote;

    @Override
    protected void processInternal(ProcessContext context) {
        CreateOrderParam createOrderParam = context.get("createOrderParam");
        // 转换 锁定商品库存 参数
        List<DeductProductParam.OrderItemParam> orderItemParamList =
                OrderApiMapstruct.INSTANCE.convertDeductProductOrderItemParam(createOrderParam.getOrderItemParamList());
        DeductProductParam lockProductParam = new DeductProductParam();
        lockProductParam.setOrderId(createOrderParam.getOrderId());
        lockProductParam.setOrderItemParamList(orderItemParamList);
        // 调用库存服务api,锁定商品库存
        inventoryRemote.deductProductStock(lockProductParam);
    }

    @Override
    protected void rollback(ProcessContext context) {
        CreateOrderParam createOrderParam = context.get("createOrderParam");
        // 转换 锁定商品库存 参数
        List<ReleaseProductStockParam.OrderItemParam> orderItemParamList =
                OrderApiMapstruct.INSTANCE.convertReleaseProductStockParamOrderItemParam(createOrderParam.getOrderItemParamList());
        ReleaseProductStockParam releaseProductStockParam = new ReleaseProductStockParam();
        releaseProductStockParam.setOrderId(createOrderParam.getOrderId());
        releaseProductStockParam.setOrderItemParamList(orderItemParamList);
    }

    /**
     * 一致性框架只能拦截public方法
     */
    // @ConsistencyTask(id = "rollbackDeductStock", alertActionBeanName = "tendConsistencyAlerter")
    public void doRollback(ReleaseProductStockParam releaseProductStockParam) {
        // 调用库存服务api,释放商品库存
        inventoryRemote.releaseProductStock(releaseProductStockParam);
    }
}
